package com.banshou.installs.model.net;


import android.content.Intent;

import com.banshou.installs.constant.BaseApplication;
import com.banshou.installs.constant.Config;
import com.banshou.installs.ui.activity.LoginActivity;
import com.banshou.installs.utils.SharePreUtil;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;

import java.io.IOException;

import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;
import retrofit2.HttpException;

/**
 * Created by cjq on 2018/7/27.
 * Email: stoic_yb@139.com
 * features:
 */
public abstract class Observer<T> implements io.reactivex.Observer<T> {
    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onNext(T t) {
        onNextStep(t);
    }

    @Override
    public void onError(Throwable e) {
        String message = Config.NONET;
        if (e instanceof HttpException) {
            HttpException h = (HttpException) e;
            try {
                ResponseBody exception = h.response().errorBody();
                if (exception != null && ((HttpException) e).code() == 500) {
                    String string = exception.string();
                    MyException exception1 = new Gson().fromJson(string, MyException.class);
                    message = exception1.get__exception().getMessage();
                } else if (exception != null && (((HttpException) e).code()) == 401) {
                    Intent intent = new Intent(BaseApplication.getContext(), LoginActivity.class);
                    BaseApplication.getContext().startActivity(intent);
                    SharePreUtil.clear(BaseApplication.getContext());
                }
            } catch (IOException e1) {
                e1.printStackTrace();
                ToastUtils.showShort(message);
            }
        } else if (e instanceof ErrorResponseException) {
            ResultResponse resultResponse = new Gson().fromJson(((ErrorResponseException) e).getString(), ResultResponse.class);
        }
        ToastUtils.showShort(message);
        onErrorResult();
    }

    @Override
    public void onComplete() {

    }

    protected abstract void onNextStep(T t);

    protected abstract void onErrorResult();
}
